package com.huika.dealontop.control.shops.activity;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.huika.dealontop.GlobalApp;
import com.huika.dealontop.R;
import com.huika.dealontop.config.Constants;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.control.login.activity.LoginActivity;
import com.huika.dealontop.control.myinfo.activity.ModifiedEmailActivity;
import com.huika.dealontop.control.myinfo.activity.ModifiedMobilePhoneActivity;
import com.huika.dealontop.control.nearby.activity.GMapActivity;
import com.huika.dealontop.control.pay.activity.ChoosePayModesActivity;
import com.huika.dealontop.control.pay.utils.BasePay;
import com.huika.dealontop.support.domain.SubmitBean;
import com.huika.dealontop.support.domain.UserModel;
import com.huika.dealontop.support.domain.ValidateBean;
import com.huika.dealontop.support.http.FlagResultRequest;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.support.http.rsa.RsaHelper;
import com.huika.dealontop.utils.LoginUtils;
import com.huika.dealontop.utils.PreferencesHelper;
import com.huika.dealontop.views.PromptOperatDialog;
import com.huika.dealontop.views.TitleBarHelper;
import com.huika.huikalib.utils.StringUtils;

import java.text.DecimalFormat;
import java.util.HashMap;

/**
 * @author chenyuan
 * @description：提交订单
 * @date 2015年11月16日 上午11:25:04
 */
public class SubmitOrderActivity extends BaseAct {


    public static String PRICE_COUPON = "price_coupon";
    public static String INPUT_COUPON_CODE = "input_coupon_code";
    public static String SKUPRICE = "skuPrice";
    public static String CURRENT_TOTAL_PRICE = "current_total_price";
    public static String PRODUCT_SKUID = "product_skuid";
    public static String PRODUCT_SKUNAME = "product_skuname";
    public static String PRODUCT_STOCK = "product_stock";

    private ImageView bt_plus, bt_add;// 倍数加减按钮
    private int multiNum = 1;// 倍数
    private int lastMultiNum = 1;// 倍数
    private EditText use_num_et;
    private EditText et_phone_or_mail;
    private EditText et_verfy_code_content;
    private CheckBox mail_num_cb, cell_phone_cb;
    private LinearLayout login_loy, no_login_loy;
    private LinearLayout login_loy_email, login_loy_phone;
    private LinearLayout submit_order_use_bonus_loy, submit_order_use_no_bonus_loy;//
    private TextView submit_order_use_bonus_tv;
    private TextView submit_order_use_no_bonus_tv;
    private TextView login_tv;
    private TextView cell_phone_modify_tv;
    private TextView mail_modify_tv;
    private TextView total_price_tv;
    private TextView unit_price_tv;
    private TextView cell_phone_num_tv;
    private TextView mail_num_tv;
    private TextView submint_name_tv;
    private TextView btn_verfy_code;
    private TextView rb_price_tv;//选中的面值
    private TextView modify_tv;//选中 文案
    private CheckBox num_cb;//选中 图标
    private Button btn_submit_order;
    private String paymentOrderId;//支付单号
    private LinearLayout has_select_coupon_loy;


    private CountDownTimer codeReqCountDownTimer;

    private HashMap<String, String> datas = new HashMap<String, String>();
    private LoginUtils loginUtils;
    private String merchantName = "";//名称
    private String skuName = "";//套餐名称
    private int skuStock;//套餐库存
    private Double salePrice;//单价
    private String couponPrice = "";//优惠券价
    private String discountPrice = "";//折扣价
    private Double couponDiscountPrice = 0.0;//折扣率

    private String vouchersID;//优惠券Id
    private String vouchersCode;//优惠码
    private int cityID;
    private Long skuID;
    private String couponType = "";
    private int validateStatus = 0;
    private String hasSelectCouponNum;
    private int tempCoup;
    private DecimalFormat format=new DecimalFormat("0.00");
    private int flag=0;

    @Override
    protected void initData() {
        super.initData();
        merchantName = getIntent().getStringExtra(GMapActivity.MERCHANTNAME);
        skuName = getIntent().getStringExtra(PRODUCT_SKUNAME);
        skuStock = getIntent().getIntExtra(PRODUCT_STOCK, 0);
        salePrice = getIntent().getDoubleExtra(SKUPRICE, 0);
        cityID = getIntent().getIntExtra(UseBonusActivity.CITYID, 0);
        skuID = getIntent().getLongExtra(PRODUCT_SKUID, 0);

        Log.d("cy", "merchantName: salePrice: cityID: skuID:skuName" + merchantName + salePrice + cityID + skuID + skuName);
    }

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_submit_order);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        new TitleBarHelper(this, R.string.common_empty, R.string.common_empty, R.string.submit_order_title).setRightPop();
        loginUtils = new LoginUtils(this);
        bt_plus = (ImageView) findViewById(R.id.bt_plus);
        bt_add = (ImageView) findViewById(R.id.bt_add);
        use_num_et = (EditText) findViewById(R.id.use_num_et);
        use_num_et.setEnabled(true);
        et_phone_or_mail = (EditText) findViewById(R.id.et_phone_or_mail);
        use_num_et.addTextChangedListener(watcher);

        mail_num_cb = (CheckBox) findViewById(R.id.mail_num_cb);
        cell_phone_cb = (CheckBox) findViewById(R.id.cell_phone_cb);
        num_cb = (CheckBox) findViewById(R.id.num_cb);
        num_cb.setBackgroundResource(R.mipmap.common_select_choise_icon);
        login_loy = (LinearLayout) findViewById(R.id.login_loy);
        login_loy_phone = (LinearLayout) findViewById(R.id.login_loy_phone);
        login_loy_email = (LinearLayout) findViewById(R.id.login_loy_email);
        login_loy_phone.setOnClickListener(this);
        login_loy_email.setOnClickListener(this);
        no_login_loy = (LinearLayout) findViewById(R.id.no_login_loy);
        submit_order_use_bonus_tv = (TextView) findViewById(R.id.submit_order_use_bonus_tv);
        submit_order_use_bonus_loy = (LinearLayout) findViewById(R.id.submit_order_use_bonus_loy);
        submit_order_use_no_bonus_tv = (TextView) findViewById(R.id.submit_order_use_no_bonus_tv);
        submit_order_use_no_bonus_loy = (LinearLayout) findViewById(R.id.submit_order_use_no_bonus_loy);
        has_select_coupon_loy = (LinearLayout) findViewById(R.id.has_select_coupon_loy);
        rb_price_tv = (TextView) findViewById(R.id.rb_price_tv);
        submint_name_tv = (TextView) findViewById(R.id.submint_name_tv);
        btn_verfy_code = (TextView) findViewById(R.id.btn_verfy_code);
        cell_phone_num_tv = (TextView) findViewById(R.id.cell_phone_num_tv);
        mail_num_tv = (TextView) findViewById(R.id.mail_num_tv);
        et_verfy_code_content = (EditText) findViewById(R.id.et_verfy_code_content);

        et_verfy_code_content.setEnabled(false);
        btn_verfy_code.setOnClickListener(this);
        submint_name_tv.setText((TextUtils.isEmpty(skuName) ? "" : "["+skuName+"]")+(TextUtils.isEmpty(merchantName) ? "" : merchantName));
        findViewById(R.id.num_cb).setSelected(true);
        modify_tv = (TextView) findViewById(R.id.modify_tv);
        modify_tv.setText(getString(R.string.submit_order_modify_change));
        modify_tv.setOnClickListener(this);
        login_tv = (TextView) findViewById(R.id.login_tv);
        total_price_tv = (TextView) findViewById(R.id.total_price_tv);

        setLimitTextVis();
        unit_price_tv = (TextView) findViewById(R.id.unit_price_tv);
        unit_price_tv.setText("" + new DecimalFormat("#").format(salePrice));
        cell_phone_modify_tv = (TextView) findViewById(R.id.cell_phone_modify_tv);
        mail_modify_tv = (TextView) findViewById(R.id.mail_modify_tv);
        btn_submit_order = (Button) findViewById(R.id.btn_submit_order);
        submit_order_use_bonus_tv.setOnClickListener(this);
        mail_modify_tv.setOnClickListener(this);
        btn_submit_order.setOnClickListener(this);
        cell_phone_modify_tv.setOnClickListener(this);
        login_tv.setOnClickListener(this);
        bt_plus.setOnClickListener(this);
        bt_add.setOnClickListener(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(PreferencesHelper.getInstance().getString(CURRENT_TOTAL_PRICE))) {
            int tempCurren = Integer.parseInt(PreferencesHelper.getInstance().getString(CURRENT_TOTAL_PRICE));
            if (tempCurren >= 99) {
                submit_order_use_bonus_loy.setVisibility(View.VISIBLE);
                submit_order_use_no_bonus_loy.setVisibility(View.GONE);
                setToatalPrice(tempCurren);

            } else {
                submit_order_use_bonus_loy.setVisibility(View.GONE);
                submit_order_use_no_bonus_loy.setVisibility(View.VISIBLE);
            }


        } else {
            setToatalPrice(Integer.parseInt(new DecimalFormat("#").format(salePrice)) * multiNum);
        }

        if (has_select_coupon_loy.getVisibility() == View.VISIBLE) {
            submit_order_use_bonus_loy.setVisibility(View.GONE);
            submit_order_use_no_bonus_loy.setVisibility(View.GONE);
        }

        if (loginUtils.isLogin()) {
            login_loy.setVisibility(View.VISIBLE);
            no_login_loy.setVisibility(View.GONE);

            if (!TextUtils.isEmpty(GlobalApp.getInstance().getUserModel().getPhone()) && !TextUtils.isEmpty(GlobalApp.getInstance().getUserModel().getEmail())) {
                login_loy_phone.setVisibility(View.VISIBLE);
                login_loy_email.setVisibility(View.VISIBLE);
                cell_phone_num_tv.setText(dealStrPhone(GlobalApp.getInstance().getUserModel().getPhone()));
                cell_phone_cb.setBackgroundResource(R.mipmap.common_select_choise_icon);
                mail_num_tv.setText(dealStrEmail(GlobalApp.getInstance().getUserModel().getEmail()));
//                mail_num_cb.setBackgroundResource(R.mipmap.common_select_choise_icon);
            } else if (!TextUtils.isEmpty(GlobalApp.getInstance().getUserModel().getPhone()) && TextUtils.isEmpty(GlobalApp.getInstance().getUserModel().getEmail())) {
                login_loy_phone.setVisibility(View.VISIBLE);
                login_loy_email.setVisibility(View.GONE);
                cell_phone_num_tv.setText(dealStrPhone(GlobalApp.getInstance().getUserModel().getPhone()));
                cell_phone_cb.setBackgroundResource(R.mipmap.common_select_choise_icon);
            } else if (!TextUtils.isEmpty(GlobalApp.getInstance().getUserModel().getEmail()) && TextUtils.isEmpty(GlobalApp.getInstance().getUserModel().getPhone())) {
                login_loy_phone.setVisibility(View.GONE);
                login_loy_email.setVisibility(View.VISIBLE);
                mail_num_tv.setText(dealStrEmail(GlobalApp.getInstance().getUserModel().getEmail()));
                mail_num_cb.setBackgroundResource(R.mipmap.common_select_choise_icon);
            } else {
                /**第三方登录。没有手机也没有邮箱，显示未登录的界面*/
                login_loy.setVisibility(View.GONE);
                no_login_loy.setVisibility(View.VISIBLE);
            }

            if (flag==2){
                cell_phone_cb.setBackgroundResource(R.mipmap.common_unselect_choise_icon);
                mail_num_cb.setBackgroundResource(R.mipmap.common_select_choise_icon);
            }
        } else {
            no_login_loy.setVisibility(View.VISIBLE);
            login_loy.setVisibility(View.GONE);
        }
    }


    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {

            case R.id.left:
                finish();
                break;
            case R.id.login_loy_phone:
                flag=1;
                cell_phone_cb.setBackgroundResource(R.mipmap.common_select_choise_icon);
                mail_num_cb.setBackgroundResource(R.mipmap.common_unselect_choise_icon);
                break;
            case R.id.login_loy_email:
                flag=2;
                cell_phone_cb.setBackgroundResource(R.mipmap.common_unselect_choise_icon);
                mail_num_cb.setBackgroundResource(R.mipmap.common_select_choise_icon);
                break;

            case R.id.bt_plus:
                if (multiNum == 1) {
                    bt_plus.setClickable(false);
                } else {
                    bt_plus.setClickable(true);

//                    if (tempCoup > 0 || !TextUtils.isEmpty(discountPrice)) {
//                        if (Integer.parseInt(new DecimalFormat("#").format(salePrice)) * (multiNum - 1) < 99) {
//                            showToastMsg(getString(R.string.submit_order_use_no_bonus));
//                        } else {
//                            use_num_et.setText(--multiNum + "");
//                        }
//                    } else {
//                        use_num_et.setText(--multiNum + "");
//                    }
//                    bt_add.setClickable(true);

                    if (tempCoup > 0 || !TextUtils.isEmpty(discountPrice)) {
                        if (Integer.parseInt(new DecimalFormat("#").format(salePrice)) * (multiNum - 1) < 99) {
//                            showToastMsg(getString(R.string.submit_order_use_no_bonus));
                            confirmDialog();

                            return;
                        }
                    }
                    use_num_et.setText(--multiNum + "");
                    bt_add.setClickable(true);
                }
                setLimitTextVis();
                setToatalPrice(Integer.parseInt(new DecimalFormat("#").format(salePrice)) * multiNum);


                break;
            case R.id.bt_add:
                if (multiNum == skuStock) {
                    bt_add.setClickable(false);
                } else {
                    bt_add.setClickable(true);
                    use_num_et.setText(++multiNum + "");
                    bt_plus.setClickable(true);
                }
                setToatalPrice(Integer.parseInt(new DecimalFormat("#").format(salePrice)) * multiNum);
                setLimitTextVis();
                break;

            case R.id.submit_order_use_bonus_tv:
                if (!loginUtils.isLogin()) {
                    showActivity(aty, LoginActivity.class);
                    return;
                }
                Intent intent = new Intent(SubmitOrderActivity.this, UseBonusActivity.class);
                intent.putExtra(UseBonusActivity.CITYID, cityID);
                intent.putExtra(UseBonusActivity.HASSELECTCOUPONNUM, hasSelectCouponNum);
                startActivityForResult(intent, 2000);
                PreferencesHelper.getInstance().setString(CURRENT_TOTAL_PRICE, Integer.parseInt(new DecimalFormat("#").format(salePrice)) * multiNum + "");

                break;
            case R.id.login_tv:
                showActivity(SubmitOrderActivity.this, LoginActivity.class);
                break;
            case R.id.cell_phone_modify_tv:
                showActivity(SubmitOrderActivity.this, ModifiedMobilePhoneActivity.class);
                break;
            case R.id.mail_modify_tv:
                showActivity(SubmitOrderActivity.this, ModifiedEmailActivity.class);
                break;
            case R.id.btn_submit_order:
                if (loginUtils.isLogin()) {
                    if (no_login_loy.getVisibility() == View.VISIBLE && GlobalApp.getInstance().getUserModel().getIsThird() == 1) {
                        /**第三方登录，可以不用输入手机邮箱，直接提交*/
                        submitOrder();
                        return;
                    } else {
                        submitOrder();
                    }
                } else {
                    if (!TextUtils.isEmpty(getInputStr(et_phone_or_mail))) {
                        if (!TextUtils.isEmpty(getInputStr(et_verfy_code_content))) {
                            submitOrder();
                        } else {
                            showToastMsg(getString(R.string.my_address_mobile_code_des));
                        }
                    } else {
                        showToastMsg(getString(R.string.register_code_empty_phone_number_des));
                    }
                }
                break;
            case R.id.modify_tv:
                Intent intentL = new Intent(SubmitOrderActivity.this, UseBonusActivity.class);
                intentL.putExtra(UseBonusActivity.CITYID, cityID);
                intentL.putExtra(UseBonusActivity.HASSELECTCOUPONNUM, hasSelectCouponNum);
                startActivityForResult(intentL, 2000);
                PreferencesHelper.getInstance().setString(CURRENT_TOTAL_PRICE, Integer.parseInt(new DecimalFormat("#").format(salePrice)) * multiNum + "");
                break;
            case R.id.btn_verfy_code:
                if (TextUtils.isEmpty(getInputStr(et_phone_or_mail))) {
                    showToastMsg(getString(R.string.register_code_empty_phone_number_des));
                    return;
                }
                getValidate(Constants.ValidateType.FAST_REGISTER);
                break;
        }
    }

    private void setToatalPrice(int tempCurrenTotal) {
        use_num_et.setEnabled(true);
        //优惠券情况
        if (tempCoup > 0) {
            use_num_et.setEnabled(false);
            /**总价<优惠券*/
            if (tempCoup >= tempCurrenTotal) {
                total_price_tv.setText(getString(R.string.common_taishu_unit) + Integer.parseInt(format.format(salePrice)) * multiNum);
                showToastMsg(getString(R.string.submit_order_bonus_tips));
                has_select_coupon_loy.setVisibility(View.GONE);
                tempCoup = 0;
            } else {
                total_price_tv.setText(getString(R.string.common_taishu_unit) + format.format(tempCurrenTotal - tempCoup));
            }
            return;
        }
        //折扣率情况
        if (couponDiscountPrice > 0 && couponDiscountPrice < 1) {
            //折扣率，前提couponPrice="";
            use_num_et.setEnabled(false);
            total_price_tv.setText(getString(R.string.common_taishu_unit) + format.format(couponDiscountPrice * Integer.parseInt(new DecimalFormat("#").format(salePrice)) * multiNum));
            return;
        }
        total_price_tv.setText(getString(R.string.common_taishu_unit) + format.format(tempCurrenTotal));

    }

    private void setLimitTextVis() {

        if (Integer.parseInt(new DecimalFormat("#").format(salePrice)) * multiNum >= 99) {
            submit_order_use_bonus_loy.setVisibility(View.VISIBLE);
            submit_order_use_no_bonus_loy.setVisibility(View.GONE);

        } else {
            submit_order_use_bonus_loy.setVisibility(View.GONE);
            submit_order_use_no_bonus_loy.setVisibility(View.VISIBLE);

        }

        if (has_select_coupon_loy.getVisibility() == View.VISIBLE) {
            submit_order_use_bonus_loy.setVisibility(View.GONE);
            submit_order_use_no_bonus_loy.setVisibility(View.GONE);
        }

    }


    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            int currentMulti = 1;// 默认为1倍

            if (s != null && !s.equals("")) {
                int a = 0;
                try {
                    a = Integer.parseInt(s.toString());
                } catch (NumberFormatException e) {
                    a = 0;
                }
                if (a > skuStock) {
                    use_num_et.setText("" + skuStock);
                }

                use_num_et.setSelection(use_num_et.getText().toString().trim().length());// 设置光标位置

                currentMulti = StringUtils.toInt(use_num_et.getText().toString()
                        .trim(), 1);// 得到输入的倍数

                multiNum = currentMulti;// 赋值
                setToatalPrice(Integer.parseInt(new DecimalFormat("#").format(salePrice)) * multiNum);
                setLimitTextVis();
                return;
            }

            if (s.equals("")) {
                total_price_tv.setText(getString(R.string.common_taishu_unit) + format.format(Integer.parseInt(new DecimalFormat("#").format(salePrice)) * currentMulti));
                multiNum = currentMulti;// 赋值,1倍
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

            if (start > 1) {
                int num = Integer.parseInt(s.toString());
                if (num > skuStock) {
                    s = "" + skuStock;
                }
                return;
            }
        }
    };

    private void submitOrder() {

//        userID	用户ID(RSA加密) (type=1 填写)
//        account	账号（RSA加密）(type=2 填写)
//        validate	验证码 (type=2 填写)
//        loginType	注册或登录类型（1.手机号码，2.邮箱地址） (type=2 填写)
//        type	类型（1.已登录，2.未登录）(type=2 填写)
//        registerSource	1-网站 2-android 3-ios (type=2 填写)


        showLoadingDialog(getString(R.string.common_loading));
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        if (loginUtils.isLogin()) {
            ajaxParams.putCommonTypeParam("type", "1");//类型（1.已登录，2.未登录）(type=2 填写)
            getUserId(ajaxParams);
        } else {
            ajaxParams.putCommonTypeParam("type", "2");
            ajaxParams.putCommonTypeParam("validate", RsaHelper.encryptDataFromStr(getInputStr(et_verfy_code_content), JSONWrapAjaxParams.publicKey));
            ajaxParams.putCommonTypeParam("account", getInputStr(et_phone_or_mail));
            if (getInputStr(et_phone_or_mail).contains("@")) {
                ajaxParams.putCommonTypeParam("loginType", "2");//注册或登录类型（1.手机号码，2.邮箱地址） (type=2 填写)
            } else {
                ajaxParams.putCommonTypeParam("loginType", "1");//注册或登录类型（1.手机号码，2.邮箱地址） (type=2 填写)
            }

        }

        if (!TextUtils.isEmpty(vouchersID)) {
            if (couponType.equals("1")) {
                ajaxParams.putCommonTypeParam("vouchersID", vouchersID);//优惠券Id
            }
        }

        if (!TextUtils.isEmpty(vouchersCode)) {
            if (couponType.equals("2")) {
                ajaxParams.putCommonTypeParam("discountCode", vouchersCode);//优惠码
            }
        }


        ajaxParams.putCommonTypeParam("skuID", skuID);
        ajaxParams.putCommonTypeParam("quantity", multiNum + "");

        ajaxParams.putCommonTypeParam("cityID", cityID);
        ajaxParams.putCommonTypeParam("registerSource", Constants.RegisterSource.ANDROID);

        FormResultRequest<SubmitBean> getResultRequest = new FormResultRequest<SubmitBean>(
                UrlConstants.GENERATEORDER, submitOrderReq, this,
                new TypeToken<RequestResult<SubmitBean>>() {
                }.getType());
        getResultRequest.setRequestParams(ajaxParams);
        executeRequest(getResultRequest);

    }

    private void getUserId(JSONWrapAjaxParams ajaxParams) {
        long u_id = GlobalApp.getInstance().getUserId();
        ajaxParams.putCommonTypeParam("userId", u_id);
    }

    private Response.Listener<RequestResult<SubmitBean>> submitOrderReq = new Response.Listener<RequestResult<SubmitBean>>() {

        @Override
        public void onResponse(RequestResult<SubmitBean> result) {
            if (result.flag == 1) {
                SubmitBean rs = result.getRs();
                paymentOrderId = rs.getPaymentOrderId();
                Intent intent = new Intent(SubmitOrderActivity.this, ChoosePayModesActivity.class);
                intent.putExtra(BasePay.PAYORDERNO, paymentOrderId);
                intent.putExtra(BasePay.PHONE, rs.getPhone());
                intent.putExtra(BasePay.USERID, rs.getUserID());
                showActivity(SubmitOrderActivity.this, intent);

                if (rs.getUserID() != 0) {
                    //未登录,将返回的结果设置到UserModel
                    UserModel userModel = new UserModel();
                    userModel.setCouponQuantity(rs.getCouponQuantity());
                    userModel.setEmail(rs.getEmail());
                    userModel.setEvaluateQuantity(rs.getEvaluateQuantity());
                    userModel.setFreQuent(rs.getFreQuent());
                    userModel.setUserHeadImage(rs.getUserHeadImage());
                    userModel.setOrderQuantity(rs.getOrderQuantity());
                    userModel.setPendingPayment(rs.getPendingPayment());
                    userModel.setToBeUser(rs.getToBeUser());
                    userModel.setWaitComments(rs.getWaitComments());
                    userModel.setPhone(rs.getPhone());
                    userModel.setReferralCode(rs.getReferralCode());
                    userModel.setNickName(rs.getNickName());
                    userModel.setUserID(rs.getUserID());

                    GlobalApp.getInstance().setUserModel(userModel);
                }


                PreferencesHelper.getInstance().setString(CURRENT_TOTAL_PRICE, "");
                finish();
            }
            dismissLoadingDialog();

        }
    };

    @Override
    public void onErrorResponse(VolleyError error) {
        // TODO Auto-generated method stub
        super.onErrorResponse(error);
        dismissLoadingDialog();
        error.getMessage();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode < 0) {
            return;
        }
        if (data != null) {
            Log.d("cy", "data:" + data);
            has_select_coupon_loy.setVisibility(View.VISIBLE);
            submit_order_use_bonus_loy.setVisibility(View.GONE);
            datas = (HashMap<String, String>) data.getExtras().getSerializable(PRICE_COUPON);
            if (datas != null) {
//                int	type:类型（1 使用优惠券 2 使用优惠码）
//                long	ID: （优惠券/优惠码ID）
//                string	activityType:优惠码类型（1代金券，2折扣）
//                string	discountAmount:优惠金额
//                string	discount:折扣率
                couponType = datas.get("type");
                if (datas.get("type").equals("1")) {
                    rb_price_tv.setText(String.format(getString(R.string.my_coupon_unit_des), new DecimalFormat("#").format(Double.parseDouble(datas.get("discountAmount")))));
                    vouchersID = datas.get("ID");
                } else {
                    vouchersCode = data.getStringExtra(INPUT_COUPON_CODE);
                    if (datas.get("activityType").equals("1")) {
                        //代金券
                        rb_price_tv.setText(String.format(getString(R.string.my_coupon_unit_des), new DecimalFormat("#").format(Double.parseDouble(datas.get("discountAmount")))));
                    } else {
                        //折扣
                        rb_price_tv.setText(String.format(getString(R.string.common_discount_des), new DecimalFormat("#").format(Double.parseDouble(datas.get("discount")) * 100)));
                        couponDiscountPrice = (Double.parseDouble(datas.get("discount")));
                        discountPrice = new DecimalFormat("#").format(Double.parseDouble(datas.get("discount")));
                    }

                }
                couponPrice = new DecimalFormat("#").format(Double.parseDouble(datas.get("discountAmount")));
                hasSelectCouponNum = datas.get("discountAmount");
                if (!TextUtils.isEmpty(couponPrice))
                    tempCoup = Integer.parseInt(couponPrice);
            }


        }
    }

    public void getValidate(int type) {
        showLoadingDialog(getString(R.string.common_loading));
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("account", getInputStr(et_phone_or_mail));
        if (getInputStr(et_phone_or_mail).contains("@")) {
            ajaxParams.putCommonTypeParam("accType", Constants.AccountType.EMAIL);
        } else {
            ajaxParams.putCommonTypeParam("accType", Constants.AccountType.PHONE);
        }

        ajaxParams.putCommonTypeParam("type", type);
        ajaxParams.putCommonTypeParam("registerSource", Constants.RegisterSource.ANDROID);
        FlagResultRequest<ValidateBean> request = new FlagResultRequest<>(UrlConstants.GETSMSVERIFICATION,
                new Response.Listener<RequestResult<ValidateBean>>() {
                    @Override
                    public void onResponse(RequestResult<ValidateBean> arg0) {
                        dismissLoadingDialog();
                        if (arg0.flag == 1) {
                            codeReqCountDownTimer = new CountDownTimer(120000, 1000) {

                                @Override
                                public void onTick(long millisUntilFinished) {
                                    btn_verfy_code.setText(String.format(getString(R.string.register_code_time), millisUntilFinished / 1000));
                                    btn_verfy_code.setEnabled(false);
                                }

                                @Override
                                public void onFinish() {
                                    btn_verfy_code.setText(getString(R.string.register_get_vertification));
                                    btn_verfy_code.setEnabled(true);
                                }
                            };
                            codeReqCountDownTimer.start();
                            et_verfy_code_content.setEnabled(true);

                            showToastMsg(arg0.msg);
                        } else {
                            if (arg0.getRs() != null) {
                                validateStatus = arg0.getRs().status;//在已注册的时候返回，其他时候没有为“rs”:null

                                if (validateStatus == 1) {
                                    getValidate(Constants.ValidateType.FAST_LOGGING);
                                } else {
                                    showToastMsg(arg0.msg);
                                }
                                Log.d("cy", "arg0.getRs().status=" + validateStatus);
                            } else {
                            }
                        }

                    }

                }, this, new TypeToken<RequestResult<ValidateBean>>() {
        }.getType());
        request.setRequestParams(ajaxParams);
        executeRequest(request);
    }

    private boolean checkPhone(String inputStr) {

        if (inputStr.startsWith("08") || inputStr.startsWith("06") || inputStr.startsWith("09")) {
            return true;
        } else {
            showToastMsg(R.string.my_address_mobile_error);
            return false;
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PreferencesHelper.getInstance().setString(CURRENT_TOTAL_PRICE, "");
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    private String dealStrPhone(String str) {
        StringBuilder sb = new StringBuilder();
        sb.append(str.substring(0, 3));
        for (int i = 3; i < str.length() - 3; i++) {
            sb.append("*");
        }
        sb.append(str.substring(str.length() - 3, str.length()));
        Log.d("cy", "加密后的电话为：" + sb.toString());
        return sb.toString();
    }

    private String dealStrEmail(String str) {
        StringBuilder sb = new StringBuilder();

        String arr[] = str.split("@");

        sb.append(arr[0].substring(0, 3));
        for (int i = 3; i < arr[0].length(); i++) {
            sb.append("*");
        }
        sb.append("@" + arr[1]);
        Log.d("cy", "加密后的邮箱为：" + sb.toString());
        return sb.toString();
    }

    private void confirmDialog() {

        final PromptOperatDialog dialog_confirm = new PromptOperatDialog(SubmitOrderActivity.this, View.inflate(this, R.layout.submit_confirm_dialog, null));
        dialog_confirm.setTitleGone();
        dialog_confirm.getConfirmBtn().setText(getString(R.string.register_confirm));
        dialog_confirm.getCancelBtn().setText(getString(R.string.common_calcle));
        dialog_confirm.setConfirmClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_confirm.dismiss();
                //优惠券价格置0,折扣率置0，并隐藏已经选择优惠券的布局，倍数显示减1，已经选中的优惠券值为空
                tempCoup = 0;
                couponDiscountPrice = 0.0;//值与discountPrice相等，只是类型不同
                has_select_coupon_loy.setVisibility(View.GONE);
                use_num_et.setText(--multiNum + "");
                setLimitTextVis();
                setToatalPrice(Integer.parseInt(new DecimalFormat("#").format(salePrice)) * multiNum);
                hasSelectCouponNum = "";
                discountPrice = "";
                vouchersID="";
                vouchersCode="";
            }
        });
        dialog_confirm.setCancelClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_confirm.dismiss();
            }
        });
        dialog_confirm.show();
    }

}
